package cz.fit.vutbr.pis2012.augeaswh.managers;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.sun.org.apache.xpath.internal.operations.Or;

import cz.fit.vutbr.pis2012.augeaswh.persistence.Order;
import cz.fit.vutbr.pis2012.augeaswh.persistence.OrdersStockType;
import cz.fit.vutbr.pis2012.augeaswh.persistence.StockType;

@Stateless
public class OrderedItemsManager {
	@PersistenceContext
	EntityManager em;
	
	@SuppressWarnings("unchecked")
	public List<OrdersStockType> getOrderedItems(Order order) {
		return em.createQuery("SELECT o FROM OrdersStockType o WHERE o.order.id = :id").setParameter("id", order.getId()).getResultList();
	}
	
	public int getOrderedItemsCount(Order order) {
		return this.getOrderedItems(order).size();
	}
	
	public BigDecimal getOrderedItemsAmountSum(Order order) {
		BigDecimal sum=new BigDecimal(0);
		Iterator<OrdersStockType> it = this.getOrderedItems(order).iterator();
		while(it.hasNext()) {
			OrdersStockType o = (OrdersStockType)it.next();
			sum=sum.add(o.getAmmount());
		}
		return sum; 
	}
	
	public BigDecimal getOrderedItemsPriceSum(Order order) {
		BigDecimal sum=new BigDecimal(0);
		for(OrdersStockType o : this.getOrderedItems(order))
		{
			sum=sum.add(
					o.getAmmount().multiply(
							o.getStockType().getPrice()
					)
			);
		}
		return sum;
	}
	
	@SuppressWarnings("unchecked")
	public List<StockType> getNotOrderedStockTypes(Order o) {
		 return em.createQuery(
				"SELECT st FROM StockType st WHERE not exists " +
					"(SELECT ost.ammount FROM OrdersStockType ost " +
		 			"WHERE ost.order.id = :id AND ost.stockType.id = st.id)" +
		 		" ORDER BY st.name, st.productClass").
		 		setParameter("id", o.getId()).getResultList();
	}
	
	public void save(OrdersStockType ost) {
		em.merge(ost);
	}
	
	public void delete(OrdersStockType ost) {
		em.remove(em.merge(ost));
	}
}
